<template>
  <div style="margin-top: 50px">
    <el-form :model="value" :rules="rules" ref="HomePopForm" label-width="120px" style="width: 600px" size="small">
      <el-form-item label="头部底图：" prop="productCategoryId">
        <single-upload v-model="value.bgPic" tip="请上传 750*660px 的图片"></single-upload>
      </el-form-item>
      <el-form-item label="第一个图片：">
         <single-upload v-model="value.pic1" tip="请上传 750*80px 的图片"></single-upload>
      </el-form-item>
      <el-form-item label="第二个图片：" prop="productCategoryId">
        <single-upload v-model="value.pic2" tip="请上传 750*200px 的图片"></single-upload>
      </el-form-item>
      <el-form-item label="标题：" prop="productCategoryId">
        <el-input v-model="value.listTitle"></el-input>
      </el-form-item>
      <el-form-item label="关联商品：" required >
        <el-table ref="productRelationTable" :data="value.productList"
                style="width: 100%;" border v-if="value.productList.length>0">
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="商品名称" width="276" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
         <el-table-column v-if="isEdit" label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       @click="handleDeleteProduct(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
      <el-button size="mini"  class="btn-add" @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <!-- <el-form-item label="选择关联商品：" class="select-product">
        <el-select v-model="value.listProducts" multiple collapse-tags filterable placeholder="请选择">
          <el-option
            v-for="item in value.productList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <p class="tips">(可输入商品名称快速定位该商品)</p>
      </el-form-item> -->
      <el-form-item style="text-align: center">
          <!-- <el-button size="medium" @click="handlePrev">上一步，填写商品促销</el-button> -->
         <el-button type="primary" size="medium" @click="handleFinishCommit">提交</el-button>
      </el-form-item>
    </el-form>
     <el-dialog title="选择商品" :visible.sync="selectDialogVisible" width="50%">
      <el-input v-model="dialogData.listQuery.keyword"
                style="width: 250px;margin-bottom: 20px"
                size="small"
                placeholder="商品名称搜索">
        <el-button slot="append" icon="el-icon-search" @click="handleSelectSearch()">点击搜索</el-button>
      </el-input>
      <el-table :data="dialogData.list"
                @selection-change="handleDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img style="max-width: 260px;max-height:60px;" :src="scope.row.pic" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">{{moneyIcon}}{{scope.row.price}}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="dialogData.listQuery.pageNum"
          :page-size="dialogData.listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="dialogData.total">
        </el-pagination>
      </div>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectDialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
 
  import SingleUpload from '@/components/Upload/singleUpload'
  // import {fetchList as fetchDepotList} from '@/api/depository'
  import {fetchList as fetchProductList} from '@/api/product';
  export default {
    name: "ProductInfoDetail",
    components:{SingleUpload},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        moneyIcon:process.env.MONEY_ICON,
           //日期选择器配置
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          }
        },
       rules:{
           
       },
      dialogData:{
        list: null,
        total: null,
        multipleSelection:[],
        listQuery:{
          keyword: null,
          pageNum: 1,
          pageSize: 5,
          publishStatus:1,
          verifyStatus:1,
        },
        depotId:null
      },
      selectDialogVisible:false,//选择商品的弹窗
      };
    },
    created() {
    //   this.getProductCateList();
    //   this.getBrandList();
      // this.getDepotList();
    },
    // computed:{
    //   //商品的编号
    //   productId(){
    //     return this.value.id;
    //   },
      
    // },
    watch: {
    //   productId:function(newValue){
    //     if(!this.isEdit)return;
    //     if(this.hasEditCreated)return;
    //     if(newValue===undefined||newValue==null||newValue===0)return;
    //     this.handleEditCreated();
    //   },
    //   selectProductCateValue: function (newValue) {
    //     console.log(newValue);
    //     if (newValue != null && newValue.length === 2) {
    //       this.value.productCategoryId = newValue[1];
    //       this.value.productCategoryName= this.getCateNameById(this.value.productCategoryId);
    //     } else {
    //       this.value.productCategoryId = null;
    //       this.value.productCategoryName=null;
    //     }
    //   }
    },
    methods: {
      handleDeleteProduct(index,row){
        let deleteId = row.id;
        let ids = [];
        ids.push(row.id);
        // let productList = this.subject.productList;
        // let deleteIndex = productList.indexOf(row);
        // this.subject.productList.splice(deleteIndex,1);
        this.$confirm('是否删除商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let index =  this.value.productList.indexOf(row);
          this.value.productList.splice(index,1);
        })
      },
      handleSelectProduct(){
        this.selectDialogVisible=true;
        this.getDialogList();
      },
      getDialogList(){
        fetchProductList(this.dialogData.listQuery).then(response=>{
          this.dialogData.list=response.data.list;
          this.dialogData.total=response.data.total;
        })
      },
      handleSelectSearch(){
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val){
        this.dialogData.multipleSelection = val;
      },
      handleSelectDialogConfirm(){
        let tempSelectedProducts = this.dialogData.multipleSelection
        if (tempSelectedProducts.length < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        if(this.isEdit){
          //编辑数据时，直接绑定相关产品、、新增数据时，需要把产品先记录下来，创建数据以后再进行绑定
          this.$confirm('确定进行绑定?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //this.bingingProducts(this.dialogData.multipleSelection);
            let addItems = this.dialogData.multipleSelection;
            let oldItems= this.value.productList;
            let finalItems=oldItems.concat(addItems);
            let finalIds=[];
            for(const item of finalItems){
              finalIds.push(item.id)
            };
            finalIds = Array.from(new Set(finalIds));
            let finalArr = [];
            for(const item of finalItems){
              for(const item2 of finalIds){
                if(item.id === item2){
                  finalArr.push(item);
                  finalIds.shift();
                }
              }
            }
            this.value.productList = finalArr;
            this.$forceUpdate();
          });
        }else{
          this.value.productList = this.value.productList.concat(this.dialogData.multipleSelection);
          this.$forceUpdate();
        }
       
        this.selectDialogVisible = false;//关闭弹窗
      },
      handlePrev() {
          this.$emit('prevStep')
      },
      handleFinishCommit(){
        // this.mergeProductAttrValue();
        // this.mergeProductAttrPics();
        this.$emit('finishCommit',this.isEdit);
      },
    }
  }
</script>

<style scoped>
</style>
